package gcontent.filter.site;

import gcontent.entities.Content;
import gcontent.entities.Site;
import gcontent.entities.site.SiteURL;
import gcontent.filter.error.FilterEx;
import gcontent.filter.string.FilterString;
import gcontent.filter.string.StringValue;

public class FilterSite extends FilterString {

	public void setInput(String input) throws FilterEx
	{
		FilterSiteParams.getParams(input, this);
	}
	
	public int check(Content content)
	{
		return check(content.getParentSite());
	}
	
	public int check(Site site)
	{
		String site_path;
		
		int n_strings, percentage;
		
		for(int i = 0; i < this.strings.size(); i++)
			this.strings_count[i] = 0;
		
		if(site instanceof SiteURL) {
			site_path = ((SiteURL)site).getURL().toString();
		} else {
			return (STATUS_FAILED | this.fail);
		}
		
		/* check each word */
		for(int o = 0; o < this.strings.size(); o++) {
			String [] parts = null;
			StringValue str_value = this.strings.get(o);
			int type_search = str_value.getTypeSearch();
			boolean good;
			
			good = false;
			
			switch(type_search) {
				case StringValue.STRING_BEGINS:
					if(site_path.startsWith(str_value.getValue()))
						good = true;
					break;
					
				case StringValue.STRING_ENDS:
					if(site_path.endsWith(str_value.getValue()))
						good = true;
					break;
					
				case StringValue.STRING_CONTAINS:
					if(site_path.contains(str_value.getValue()))
						good = true;
					break;
					
				case StringValue.STRING_EQUALS:
					if(site_path.equals(str_value.getValue()))
						good = true;
					break;			
					
				case StringValue.FILE_NAME: 					
					if(!(site_path.toLowerCase().contains(str_value.getValue().toLowerCase()) || str_value.getValue().equals("*")))
						return (STATUS_FAILED | this.fail);
		
					break;					
			}
			
			if(good == true) {
				this.strings_count[o]++;
			}
		}
				
		n_strings = 0;
		for(int o = 0; o < this.strings_count.length; o++) {
			if(this.strings_count[o] > 0)
				n_strings++;
		}
				
		percentage = (n_strings * 100) / this.strings_count.length;
		if(percentage >= this.min_percentage && percentage <= this.max_percentage)
			return (STATUS_OK | this.success);

		return (STATUS_FAILED | this.fail);
	}
}
